
/**
 * 重写响应头中的 cookie domain
 * @param {import('http').IncomingMessage} proxyRes - 来自目标服务器的响应
 * @param {import('http').ServerResponse} res - 发送给客户端的响应
 * @param {string} host - 目标主机
 */
const rewriteCookieDomain = (proxyRes, res, host) => {
    const originalCookies = proxyRes.headers['set-cookie'];
    if (!originalCookies) return;

    const newCookies = originalCookies.map(cookie => {
        // 用正则表达式不区分大小写地替换 domain
        return cookie.replace(/domain=([^;]+)/gi, `domain=${host}`);
    });
    res.setHeader('Set-Cookie', newCookies);
};

/**
 * 根据业务逻辑修改响应体
 * @param {object} body - 解析后的JSON响应体
 * @param {string} apiPath - 请求路径
 * @param {string} host - 目标主机
 * @param {number} port - 端口
 * @returns {object} - 修改后的响应体
 */
const modifyResponseBody = (body, apiPath, host, port) => {
    // 登录成功
    if ((body.errcode === 200 || body.errcode === "200") && apiPath === "/user/login") {
        body.data.redirect = `http://${host}:${port}`;
    }
    // 登录过期
    if (body.errcode === 402 && body.data?.redirect_url) {
        console.log(`[Vite Proxy] Modifying redirect_url for: ${apiPath}`);
        body.data.redirect_url = '/login';
    }
    return body;
};

/**
 * 通用的代理响应处理程序
 * @param {import('http').IncomingMessage} proxyRes
 * @param {import('http').IncomingMessage} req
 * @param {import('http').ServerResponse} res
 * @param {{host: string, port: number}} options
 */
const proxyResponseHandler = (proxyRes, req, res, { host, port }) => {
    rewriteCookieDomain(proxyRes, res, host);

    const apiPath = req.originalUrl.split('?')[0];
    const originalBody = [];

    proxyRes.on('data', (chunks) => originalBody.push(chunks));
    proxyRes.on('end', () => {
        const bodyString = Buffer.concat(originalBody).toString('utf8');
        let responseBody;

        try {
            responseBody = JSON.parse(bodyString);
            responseBody = modifyResponseBody(responseBody, apiPath, host, port);
        } catch (e) {
            res.end(bodyString); // 非JSON响应，直接返回
            return;
        }

        res.setHeader('Content-Type', 'application/json');
        res.end(JSON.stringify(responseBody));
    });
};

/**
 * 创建 Vite 代理配置
 * @param {object} env - 环境变量
 * @returns {import('vite').ProxyOptions}
 */
export const createProxyConfig = (env) => {
    const { 
        PHP_API_BASE_URL, 
        JAVA_API_BASE_URL, 
        LOGIN_HOST, 
        HOST, 
    } = env;
    const PROT = 5003; // 将端口号也作为配置的一部分

    const handlerOptions = { host: HOST, port: PROT };
    
    // 抽离出通用的 configure 配置
    const configureWithHandler = {
        configure: (proxy) => {
            proxy.on('proxyRes', (proxyRes, req, res) => {
                proxyResponseHandler(proxyRes, req, res, handlerOptions);
            });
        }
    };

    // 抽离出指向登录服务器的基础配置
    const baseLoginProxy = {
        target: LOGIN_HOST,
        changeOrigin: true,
        secure: false,
    };

    return {
        "/libs": {
            target: `http://localhost:${PROT}/english-view/src/`,
        },
        "/phpApi": {
            target: PHP_API_BASE_URL,
            changeOrigin: true,
            secure: false,
            selfHandleResponse: true,
            rewrite: (path) => path.replace(/^\/phpApi/, '/'),
            withCredentials: true,
            ...configureWithHandler,
        },
        "/javaApi/api": {
            target: JAVA_API_BASE_URL,
            changeOrigin: true,
            secure: false,
            selfHandleResponse: true,
            rewrite: (path) => path.replace(`/javaApi/api`, '/api'),
            ...configureWithHandler,
        },
        "/login": {
            ...baseLoginProxy,
            rewrite: (path) => path.replace(/^\/login/, '/'),
        },
        "/user/login": {
            ...baseLoginProxy,
            withCredentials: true,
            selfHandleResponse: true,
            ...configureWithHandler,
        },
        "/style": { ...baseLoginProxy },
        "/js/base": { ...baseLoginProxy },
        "/js/home/login": { ...baseLoginProxy },
    };
};
